package com.sogou.adm.bizdev.dataimport.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sogou.adm.bizdev.dataimport.vo.DataJobTrigger;

@Service
@Transactional
public class TriggerManager {
	@Autowired
	SchedulerFactoryBean schedulerFactory;

	public List<DataJobTrigger> getAll() throws SchedulerException {

		Scheduler scheduler = schedulerFactory.getScheduler();
		String[] triggerGroupNames = scheduler.getTriggerGroupNames();

		List<DataJobTrigger> triggers = new ArrayList<DataJobTrigger>();

		for (String triggerGroupName : triggerGroupNames) {
			String[] triggerNames = scheduler.getTriggerNames(triggerGroupName);
			for (String triggerName : triggerNames) {
				Trigger trigger = scheduler.getTrigger(triggerName,
						triggerGroupName);

				triggers.add(new DataJobTrigger(trigger));
			}
		}
		return triggers;
	}

	public void addTrigger(DataJobTrigger trigger) throws SchedulerException {
		CronTriggerBean cronTrigger = new CronTriggerBean();
		cronTrigger.setName(trigger.getName());
		cronTrigger.setGroup(trigger.getGroup());
		cronTrigger.setJobName(trigger.getJobName());
		cronTrigger.setJobGroup(trigger.getJobGroup());
		try {
			cronTrigger.setCronExpression(trigger.getCronExpression());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JobDetail jobDetail = schedulerFactory.getScheduler().getJobDetail(
				trigger.getJobName(), trigger.getJobGroup());
		cronTrigger.setJobDetail(jobDetail);
		schedulerFactory.getScheduler().scheduleJob(cronTrigger);
	}

	public void deleteTrigger(String triggerName, String triggergroupName)
			throws SchedulerException {
		schedulerFactory.getScheduler().unscheduleJob(triggerName,
				triggergroupName);
	}

	public DataJobTrigger get(String triggerName, String triggergroupName) throws SchedulerException {
		return new DataJobTrigger(schedulerFactory.getScheduler().getTrigger(triggerName, triggergroupName));
	}
}
